<?php
/**
 * Joomla! 1.5 component NS Pro
 *
 * @version $Id: nspro.php 2009-04-28 01:47:12 svn $
 * @author Christopher Mavros
 * @package Joomla
 * @subpackage NS Pro
 * @license GNU/GPL
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');

class NsproModelFields extends JModel {

    function __construct()
    {
        parent::__construct();

        //global $mainframe, $option;
        $mainframe = JFactory::getApplication();
        $option = JRequest::getCmd('option');
        
        include('components/com_nspro/ftypes.php');
        $this->setState('ftypes', $ftypes);

        $filter_order     = $mainframe->getUserStateFromRequest(  $option.'fld.filter_order', 'filter_order', 'ordering', 'cmd' );
        $filter_order_Dir = $mainframe->getUserStateFromRequest( $option.'fld.filter_order_Dir', 'filter_order_Dir', 'asc', 'word' );

        $this->setState('fld.filter_order', $filter_order);
        $this->setState('fld.filter_order_Dir', $filter_order_Dir);

        $array = JRequest::getVar('cid',  0, '', 'array');
        $this->setId((int)$array[0]);
    }

    function setId($id)
    {
        // Set id and wipe data
        $this->_id      = $id;
        $this->_data    = null;
    }

    function getField()
    {
        $db =& JFactory::getDBO();
        // Load the data
        if (empty( $this->_data )) {
            $query = ' SELECT * FROM `#__nspro_fields` '.
                    '  WHERE `id` = '.$this->_id;
            $db->setQuery( $query );
            $this->_data = $db->loadObject();
        }
        if (!$this->_data) {
            $this->_data = new stdClass();
            $this->_data->id = 0;
            $this->_data->name  = null;
            $this->_data->fieldtype = 0;
            $this->_data->regexp = '';
            $this->_data->required = false;
            $this->_data->published = false;
            $this->_data->show_backend = false;
            $this->_data->abovepos = false;
            $this->_data->ordering = null;
            $this->_data->value = null;
            $this->_data->notes = null;
        }
        return $this->_data;
    }

    function getFields($limit, $limitstart) {
        $db =& JFactory::getDBO();

        $query = 'SELECT * FROM `#__nspro_fields`';
        $orderby = $this->_buildContentOrderBy();
        $query .= ' '.$orderby;

        $fields = $this->_getList( $query , $limitstart, $limit);

        return $fields;
    }

    function getAllFields() {
        $db =& JFactory::getDBO();

        $query = 'SELECT * FROM `#__nspro_fields`';
        $orderby = $this->_buildContentOrderBy();
        $query .= ' '.$orderby;

        $db->setQuery($query);

        $fs = $db->loadObjectList();

        return $fs;
    }

    function getFieldCount() {
        $db =& JFactory::getDBO();

        $query = 'SELECT COUNT(`id`) FROM `#__nspro_fields`';

        $db->setQuery( $query );
        $fCount = $db->loadResult();

        return $fCount;
    }

    function store()
    {
        $db =& JFactory::getDBO();
        $row =& $this->getTable('nsfields');
        $data = JRequest::get( 'post' );

        // Bind the form fields to the nssubs table
        if (!$row->bind($data)) {
            $this->setError($db->getErrorMsg());
            return false;
        }

        // Make sure the nssubs records are valid
        if (!$row->check()) {
            $this->setError($db->getErrorMsg());
            return false;
        }

        // Store the nssubs table to the database
        if (!$row->store()) {
            $this->setError( $row->getErrorMsg() );
            return false;
        }

        return true;
    }

    function delete()
    {
        $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

        $row =& $this->getTable('nsfields');

        if (count( $cids ))
        {
            foreach($cids as $cid) {
                if (!$row->delete( $cid )) {
                    $this->setError( $row->getErrorMsg() );
                    return false;
                }
            }
        }
        return true;
    }

    function publish($i) {

        $db     =& JFactory::getDBO();

        $cid        = JRequest::getVar( 'cid', array(), '', 'array' );
        $publish    = $i;

        JArrayHelper::toInteger($cid);

        $cids = implode( ',', $cid );

        $query = 'UPDATE `#__nspro_fields`'
        . ' SET `published` = ' . (int) $publish
        . ' WHERE `id` IN ( '. $cids .' )';
        $db->setQuery( $query );
        if (!$db->query())
        {
            JError::raiseError(500, $db->getErrorMsg() );
        }

        if (count( $cid ) == 1)
        {
            $row =& $this->getTable('nsfields');
            $row->checkin( $cid[0] );
        }

        return true;
    }

    function _buildContentOrderBy() {
      //global $mainframe, $option;
      $mainframe = JFactory::getApplication();
      $option = JRequest::getCmd('option');

      $orderby = '';
      $filter_order     = $this->getState('fld.filter_order');
      $filter_order_Dir = $this->getState('fld.filter_order_Dir');

      if(!empty($filter_order) && !empty($filter_order_Dir) ){
        $orderby = ' ORDER BY `'.$filter_order.'` '.$filter_order_Dir;
      }

      return $orderby;
    }

    function orderup() {
      $row =& $this->getTable('nsfields');
      $cid  = JRequest::getVar( 'cid', array(), '', 'array' );

      $row->load( $cid[0] );

      $od = $this->getState('fld.filter_order_Dir');
      $or = $this->getState('fld.filter_order');

      if (($od == 'desc') && ($or == 'ordering')) {
        $row->move(1);
      }
      else {
        $row->move(-1);
      }

      return true;
    }

    function orderdown() {
      $row =& $this->getTable('nsfields');
      $cid  = JRequest::getVar( 'cid', array(), '', 'array' );

      $row->load( $cid[0] );

      $od = $this->getState('fld.filter_order_Dir');
      $or = $this->getState('fld.filter_order');

      if (($od == 'desc') && ($or == 'ordering')) {
        $row->move(-1);
      }
      else {
        $row->move(1);
      }

      return true;
    }

    function saveorder() {
      $db =& JFactory::getDBO();
      $cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );
      $order = JRequest::getVar( 'order', array(0), 'post', 'array' );
      $total = count($cid);

      $row =& $this->getTable('nsfields');
      $updated_ids = array();
      for ($i = 0; $i < $total; $i++) {
        $row->load((int) $cid[$i]);
        if ($row->ordering != $order[$i]) {
          $row->ordering = $order[$i];
          if (!$row->store()) {
            JError::raiseError( 500, $db->getErrorMsg() );
            return false;
          }
          $updated_ids[] = $row->id;
        }
      }

      if (count($updated_ids) > 0) {
        foreach($updated_ids as $upid) {
          $row->load((int) $upid);
          $row->reorder();
        }
      }

      return true;
    }

}
?>